package com.hanson.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hanson.api_bean.FansDetail;
import com.hanson.api_bean.ScoreOrderRequest;
import com.hanson.common.bean.*;
import com.hanson.common.exception.BusinessException;
import com.hanson.common.service.RedisService;
import com.hanson.common.util.BusinessUtil;
import com.hanson.common.util.KuaidiUtil;
import com.hanson.entity.*;
import com.hanson.mapper.*;
import com.hanson.param.SimpleOrder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderService {
    @Autowired
    private OrderBeanMapper orderBeanMapper;
    @Autowired
    private GoodsAttrValueBeanMapper goodsAttrValueBeanMapper;
    @Autowired
    private GoodsBeanMapper goodsBeanMapper;
    @Autowired
    private CartBeanMapper cartBeanMapper;
    @Autowired
    private UserAddresBeanMapper userAddresBeanMapper;
    @Autowired
    private UserBeanMapper userBeanMapper;
    @Autowired
    private SeckillGoodsBeanMapper seckillGoodsBeanMapper;
    @Autowired
    private GroupGoodsBeanMapper groupGoodsBeanMapper;
    @Autowired
    private ScoreSeqBeanMapper scoreSeqBeanMapper;
    @Autowired
    private AcctbkSeqBeanMapper acctbkSeqBeanMapper;
    @Autowired
    private SpreadInfoBeanMapper spreadInfoBeanMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private PayService payService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private OrderRefundService orderRefundService;
    @Autowired
    private CouponsBeanMapper couponsBeanMapper;
    @Autowired
    private GoodsScoreBeanMapper goodsScoreBeanMapper;
    @Autowired
    private GoodsScoreService goodsScoreService;
    @Autowired
    private SpreadMoneyBeanMapper spreadMoneyBeanMapper;
    @Autowired
    private TaskService taskService;

    public FansDetail getFansDetail(String openId, boolean queryOrder) {
        UserBean userBean = userBeanMapper.selectByOpenId(openId);
        if (null == userBean) {
            throw new BusinessException("用户信息不正确");
        }
        FansDetail fansDetail = new FansDetail();
        fansDetail.setChildId(openId);
        fansDetail.setIsSpread(userBean.getIsSpread());
        fansDetail.setIsVip(userBean.getIsVip());
        fansDetail.setIsShopkeeper(userBean.getUserType().equals("2") ? 1 : 0);
        fansDetail.setMoney(BusinessUtil.getWebAmount(userBean.getMoney()));
        fansDetail.setScore(userBean.getScore());
        fansDetail.setPhone(userBean.getPhone());
        fansDetail.setUserName(userBean.getNickName());
        fansDetail.setUserImage(userBean.getHeadImg());
        if (queryOrder) {
            fansDetail.setOrders(queryFansOrder(openId));
        }
        return fansDetail;
    }

    public List<SimpleOrder> queryFansOrder(String openId) {
        List<SimpleOrder> orders = new ArrayList<>();
        List<SpreadInfoBean> spreadInfoBeanList = spreadInfoBeanMapper.selectByChildId(openId);
        if (CollectionUtils.isNotEmpty(spreadInfoBeanList)) {
            //已完成订单
            List<OrderBean> orderBeanList = orderBeanMapper.selectByOpenId(openId, null);
            if (CollectionUtils.isNotEmpty(orderBeanList)) {
                Date date = spreadInfoBeanList.get(0).getCreateDate();

                for (OrderBean orderBean : orderBeanList) {
                    if (orderBean.getStatus() <= 1) {
                        continue;
                    }
                    if (orderBean.getCreateDate().before(date)) {
                        continue;
                    }
                    SimpleOrder simpleOrder = new SimpleOrder();
                    GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(orderBean.getGoodsId());
                    if (null != goodsBean) {
                        simpleOrder.setGoodsImage(goodsBean.getImage());
                        simpleOrder.setGoodsName(goodsBean.getGoodsName());
                    }
                    List<GoodsAttrValueBean> goodsAttrValueBeanList = goodsAttrValueBeanMapper.selectByByGoodsIdAndSuk(orderBean.getGoodsId(), orderBean.getGoodsAttr(), 1);
                    if (CollectionUtils.isNotEmpty(goodsAttrValueBeanList)) {
                        GoodsAttrValueBean goodsAttrValueBean = goodsAttrValueBeanList.get(0);
                        int spreadMoney = goodsAttrValueBean.getSpreadMoney() == null ? 0 : Integer.parseInt(goodsAttrValueBean.getSpreadMoney());
                        int speadChildMoney = goodsAttrValueBean.getSpreadChildMoney() == null ? 0 : Integer.parseInt(goodsAttrValueBean.getSpreadChildMoney());
                        if (spreadMoney > 0 || speadChildMoney > 0) {
                            List<SpreadInfoBean> childIds = spreadInfoBeanMapper.selectByChildId(openId);
                            if (CollectionUtils.isNotEmpty(childIds)) {
                                //代理商下级购买计算佣金
                                simpleOrder.setSpreadMoney(BusinessUtil.getWebAmount(speadChildMoney));
                            }
                        }
                    }
                    simpleOrder.setGoodsNum(orderBean.getTotalNum() + "");
                    simpleOrder.setGoodsPrice(BusinessUtil.getWebAmount(orderBean.getTotalPrice()));
                    simpleOrder.setPayPrice(BusinessUtil.getWebAmount(orderBean.getPayPrice()));
                    simpleOrder.setRecevieName(orderBean.getUserName());
                    simpleOrder.setOrderSeq(orderBean.getOrderId());
                    simpleOrder.setOrderTime(orderBean.getCreateDate());
                    simpleOrder.setOrderStatus(BusinessUtil.getOrderStatusName(orderBean.getStatus()));
                    orders.add(simpleOrder);
                }
            }
        }
        return orders;
    }

    @Transactional(rollbackFor = Exception.class)
    public void finishOrder(String orderId) {
        List<OrderBean> orderBeanList = orderBeanMapper.selectByOrderId(orderId);
        if (CollectionUtils.isNotEmpty(orderBeanList)) {
            this.updateStatus(5, orderId);
            //计算佣金定时任务
            taskService.saveTask(new TaskBean(3, orderId, DateFormatUtils.format(DateUtils.addDays(new Date(), 1), "yyyy-MM-dd HH:mm:ss")));
            //计算佣金
            spreadMoneyBeanMapper.updateToAccountTime(DateUtils.addDays(new Date(), 1), orderId);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public int updateAddressInfo(OrderSubmitParam orderSubmitParam, String openId) {
        UserBean userBean = userBeanMapper.selectByOpenId(openId);
        if (null == userBean) {
            throw new BusinessException("用户信息不正确");
        }
        if (userBean.getScore() < orderSubmitParam.getUserScore()) {
            throw new BusinessException("使用积分大于拥有的积分");
        }
        int userMoney = 0;
        if (!StringUtils.isEmpty(orderSubmitParam.getUserMoney())) {
            userMoney = BusinessUtil.getDbAmount(orderSubmitParam.getUserMoney());
        }
        if (userBean.getMoney() < userMoney) {
            throw new BusinessException("使用余额大于拥有的余额");
        }
        int totalReduce = userMoney + orderSubmitParam.getUserScore() * 5;
        List<OrderBean> orderBeanList = orderBeanMapper.selectByOrderId(orderSubmitParam.getOrderSeq());
        if (CollectionUtils.isNotEmpty(orderBeanList)) {
            UserAddresBean userAddresBean = userAddresBeanMapper.selectByPrimaryKey(orderSubmitParam.getAddressId());
            int totalFee = 0;
            int orderType = 0;
            int goodsId = 0;
            int totalNum = 0;
            for (OrderBean c : orderBeanList) {
                c.setRemark(orderSubmitParam.getRemark());
                c.setUserName(userAddresBean.getUserName());
                c.setUserPhone(userAddresBean.getPhone());
                c.setUserAddress(userAddresBean.getProvince() + " " + userAddresBean.getCity() + " " + userAddresBean.getDistrict() + " " + userAddresBean.getDetail());
                c.setUserScore(orderSubmitParam.getUserScore());
                c.setUserMoney(userMoney);
                c.setUserCoupons(orderSubmitParam.getCouponId());
                c.setUpdateDate(new Date());
                totalFee += c.getTotalPrice();
                orderType = c.getOrderType();
                goodsId = c.getGoodsId();
                totalNum = c.getTotalNum();
                orderBeanMapper.updateAddresById(c);
            }
            if (null != orderSubmitParam.getCouponId()) {
                //有使用优惠卷
                CouponsBean couponsBean = couponsBeanMapper.selectByPrimaryKey(orderSubmitParam.getCouponId());
                if (null == couponsBean) {
                    throw new BusinessException("优惠卷ID不正确");
                }
                if (totalFee >= BusinessUtil.getDbAmount(couponsBean.getMinAmount())) {
                    //优惠金额
                    totalFee -= BusinessUtil.getDbAmount(couponsBean.getDiscountAmount());
                }
            }
            if (orderType == 4) {
                //积分兑换
                List<GoodsScoreBean> goodsScoreBeanList = goodsScoreBeanMapper.selectByGoodsId(goodsId);
                if (CollectionUtils.isEmpty(goodsScoreBeanList)) {
                    throw new BusinessException("商品不是积分兑换商品");
                }
                GoodsScoreBean goodsScoreBean = goodsScoreBeanList.get(0);
                if (goodsScoreBean.getType() == 1) {
                    //全积分
                    if (orderSubmitParam.getUserScore() == goodsScoreBean.getScore() * totalNum) {
                        WechatRefundApiResult wechatRefundApiResult = new WechatRefundApiResult();
                        wechatRefundApiResult.setOut_trade_no(orderSubmitParam.getOrderSeq());
                        wechatRefundApiResult.setOpenid(openId);
                        wechatRefundApiResult.setTotal_fee("0");
                        payService.dealNotify(wechatRefundApiResult);
                        return 2;//无需要微信支付
                    } else {
                        throw new BusinessException("积分参数不正确");
                    }
                } else if (goodsScoreBean.getType() == 2) {
                    //积分加现金
                    if (orderSubmitParam.getUserScore() == goodsScoreBean.getScore() * totalNum) {
                        return 1;
                    } else {
                        throw new BusinessException("积分参数不正确");
                    }
                }

            } else {
                if (totalReduce > 0) {
                    //有积分支付
                    if (totalReduce > totalFee) {
                        log.error("totalReduce:{} totalFee:{}", totalReduce, totalFee);
                        throw new BusinessException("使用优惠大于商品总价");
                    }
                    if (totalReduce == totalFee) {//全部抵扣
                        WechatRefundApiResult wechatRefundApiResult = new WechatRefundApiResult();
                        wechatRefundApiResult.setOut_trade_no(orderSubmitParam.getOrderSeq());
                        String payOpenId = "";
                        if (!StringUtils.isEmpty(userBean.getMaOpenId())) {
                            payOpenId = userBean.getMaOpenId();
                        }
                        if (StringUtils.isEmpty(payOpenId) && !StringUtils.isEmpty(userBean.getMpOpenId())) {
                            payOpenId = userBean.getMpOpenId();
                        }
                        if (StringUtils.isEmpty(payOpenId)) {
                            throw new BusinessException("用户openId不正确");
                        }

                        wechatRefundApiResult.setOpenid(payOpenId);
                        wechatRefundApiResult.setTotal_fee("0");
                        payService.dealNotify(wechatRefundApiResult);
                        return 2;//无需要微信支付
                    }
                }
            }
            return 1; //微信支付
        }
        return 0;
    }

    @Transactional(rollbackFor = Exception.class)
    public String addCartOrder(String openId, CartParam cartParam) {
        String orderSeq = BusinessUtil.getOrderSeq(1);
        for (CartBean cartBean : cartParam.getList()) {
            CartBean returnBean = cartBeanMapper.selectByPrimaryKey(cartBean.getId());
            OrderBean orderBean = new OrderBean();
            orderBean.setOpenId(openId);
            orderBean.setStatus(1);
            orderBean.setOrderType(1);
            orderBean.setOrderId(orderSeq);
            orderBean.setGoodsId(returnBean.getGoodsId());
            orderBean.setGoodsAttr(returnBean.getGoodsAttr());
            orderBean.setTotalNum(cartBean.getAddNum());
            GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(orderBean.getGoodsId());
            if (null != goodsBean) {
                orderBean.setMerId(goodsBean.getMerId());
            } else {
                throw new BusinessException("商品已下架");
            }
            List<GoodsAttrValueBean> goodsAttrValueBeanList = goodsAttrValueBeanMapper.selectByByGoodsIdAndSuk(returnBean.getGoodsId(), returnBean.getGoodsAttr(), 1);
            UserBean userBean = userBeanMapper.selectByOpenId(openId);
            int totalPrice = 0;
            if (CollectionUtils.isEmpty(goodsAttrValueBeanList)) {
                log.error("【商品 goodsId = {} suk = {} 规格为空】", orderBean.getGoodsId(), orderBean.getGoodsAttr());
                if (goodsBean.getStock() <= 0) {
                    throw new BusinessException("商品" + goodsBean.getGoodsName() + "已售罄");
                }
                if (orderBean.getTotalNum() > goodsBean.getStock()) {
                    throw new BusinessException("商品" + goodsBean.getGoodsName() + "库存不足，只剩下：" + goodsBean.getStock() + "个");
                }
                if (null != userBean && userBean.getIsVip() == 1 && goodsBean.getVipPrice() != null) {
                    totalPrice = goodsBean.getVipPrice() * orderBean.getTotalNum();
                } else {
                    totalPrice = goodsBean.getPrice() * orderBean.getTotalNum();
                }
            } else {
                if (goodsAttrValueBeanList.get(0).getStock() <= 0) {
                    throw new BusinessException("商品" + goodsBean.getGoodsName() + "已售罄");
                }
                if (orderBean.getTotalNum() > goodsAttrValueBeanList.get(0).getStock()) {
                    throw new BusinessException("商品" + goodsBean.getGoodsName() + "库存不足，只剩下：" + goodsAttrValueBeanList.get(0).getStock() + "个");
                }
                if (null != userBean && userBean.getIsVip() == 1 && goodsBean.getVipPrice() != null) {
                    totalPrice = Integer.parseInt(goodsAttrValueBeanList.get(0).getVipPrice()) * orderBean.getTotalNum();
                } else {
                    totalPrice = Integer.parseInt(goodsAttrValueBeanList.get(0).getPrice()) * orderBean.getTotalNum();
                }
            }
            if (totalPrice <= 0) {
                throw new BusinessException("新增订单失败，商品价格不正确");
            }
            orderBean.setTotalPrice(totalPrice);
            orderBean.setCreateDate(new Date());
            orderBeanMapper.insert(orderBean);
            cartBeanMapper.deleteByPrimaryKey(cartBean.getId());
        }
        taskService.saveTask(new TaskBean(1, orderSeq, DateFormatUtils.format(DateUtils.addDays(new Date(), 1), "yyyy-MM-dd HH:mm:ss")));
        return orderSeq;
    }

    public String addSkillOrder(String openId, SeckillGoodsBean seckillGoodsBean) {
        SeckillGoodsBean returnBean = seckillGoodsBeanMapper.selectByPrimaryKey(seckillGoodsBean.getId());
        if (null == returnBean) {
            throw new BusinessException("当前秒杀不存在");
        }
        Date currentDate = new Date();
        if (returnBean.getStartTime().after(currentDate)) {
            throw new BusinessException("秒杀还未开始");
        }
        if (returnBean.getStopTime().before(currentDate)) {
            throw new BusinessException("秒杀已经结束");
        }
        if (seckillGoodsBean.getTotalNum() > returnBean.getNum()) {
            throw new BusinessException("购买商品数量大于限购数量：" + returnBean.getNum());
        }
        if (returnBean.getStock() <= 0) {
            throw new BusinessException("当前商品已售罄");
        }
        String orderSeq = BusinessUtil.getOrderSeq(1);
        OrderBean orderBean = new OrderBean();
        orderBean.setOrderId(orderSeq);
        //秒杀订单
        orderBean.setOrderType(2);
        orderBean.setCreateDate(new Date());
        orderBean.setOpenId(openId);
        orderBean.setStatus(1);
        orderBean.setGoodsAttr(seckillGoodsBean.getGoodsAttr());
        orderBean.setGoodsId(seckillGoodsBean.getGoodsId());
        GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(orderBean.getGoodsId());
        if (null != goodsBean) {
            orderBean.setMerId(goodsBean.getMerId());
        }
        orderBean.setTotalNum(seckillGoodsBean.getTotalNum());
        List<GoodsAttrValueBean> goodsAttrValueBeanList = goodsAttrValueBeanMapper.selectByByGoodsIdAndSuk(seckillGoodsBean.getId(), orderBean.getGoodsAttr(), 3);
        if (CollectionUtils.isEmpty(goodsAttrValueBeanList)) {
            orderBean.setTotalPrice(seckillGoodsBean.getTotalNum() * returnBean.getSeckillPrice());
        } else {
            GoodsAttrValueBean goodsAttrValueBean = goodsAttrValueBeanList.get(0);
            UserBean userBean = userBeanMapper.selectByOpenId(openId);
            int totalPrice = 0;
            if (null != userBean && userBean.getIsVip() == 1 && !StringUtils.isEmpty(goodsAttrValueBean.getVipPrice())) {
                totalPrice = Integer.parseInt(goodsAttrValueBean.getVipPrice()) * orderBean.getTotalNum();
            } else {
                totalPrice = Integer.parseInt(goodsAttrValueBean.getPrice()) * orderBean.getTotalNum();
            }
            orderBean.setTotalPrice(totalPrice);
        }
        orderBeanMapper.insert(orderBean);
        taskService.saveTask(new TaskBean(1, orderSeq, DateFormatUtils.format(DateUtils.addDays(orderBean.getCreateDate(), 1), "yyyy-MM-dd HH:mm:ss")));
        return orderSeq;
    }

    @Transactional(rollbackFor = Exception.class)
    public String addGroupOrder(String openId, GroupGoodsBean groupGoodsBean) {
        GroupGoodsBean returnBean = groupGoodsBeanMapper.selectByPrimaryKey(groupGoodsBean.getId());
        if (null == returnBean) {
            throw new BusinessException("当前拼团不存在");
        }
        Date currentDate = new Date();
        if (returnBean.getStartTime().after(currentDate)) {
            throw new BusinessException("拼团还未开始");
        }
        if (returnBean.getEndTime().before(currentDate)) {
            throw new BusinessException("拼团已经结束");
        }
        if (groupGoodsBean.getTotalNum() > returnBean.getNum()) {
            throw new BusinessException("购买商品数量大于限购数量：" + returnBean.getNum());
        }
        if (returnBean.getStock() <= 0) {
            throw new BusinessException("当前商品已售罄");
        }
        String orderSeq = BusinessUtil.getOrderSeq(1);
        OrderBean orderBean = new OrderBean();
        orderBean.setOrderId(orderSeq);
        //拼团订单
        orderBean.setOrderType(3);
        orderBean.setCreateDate(new Date());
        orderBean.setOpenId(openId);
        orderBean.setStatus(1);
        orderBean.setGoodsAttr(groupGoodsBean.getGoodsAttr());
        orderBean.setGoodsId(groupGoodsBean.getGoodsId());
        GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(orderBean.getGoodsId());
        if (null != goodsBean) {
            orderBean.setMerId(goodsBean.getMerId());
        }
        orderBean.setTotalNum(groupGoodsBean.getTotalNum());
        List<GoodsAttrValueBean> goodsAttrValueBeanList = goodsAttrValueBeanMapper.selectByByGoodsIdAndSuk(groupGoodsBean.getId(), orderBean.getGoodsAttr(), 2);
        if (CollectionUtils.isEmpty(goodsAttrValueBeanList)) {
            orderBean.setTotalPrice(groupGoodsBean.getTotalNum() * returnBean.getGroupPrice());
        } else {
            GoodsAttrValueBean goodsAttrValueBean = goodsAttrValueBeanList.get(0);
            UserBean userBean = userBeanMapper.selectByOpenId(openId);
            int totalPrice = 0;
            if (null != userBean && userBean.getIsVip() == 1 && !StringUtils.isEmpty(goodsAttrValueBean.getVipPrice())) {
                totalPrice = Integer.parseInt(goodsAttrValueBean.getVipPrice()) * orderBean.getTotalNum();
            } else {
                totalPrice = Integer.parseInt(goodsAttrValueBean.getPrice()) * orderBean.getTotalNum();
            }
            orderBean.setTotalPrice(totalPrice);
        }
        orderBeanMapper.insert(orderBean);
        taskService.saveTask(new TaskBean(1, orderSeq, DateFormatUtils.format(DateUtils.addDays(orderBean.getCreateDate(), 1), "yyyy-MM-dd HH:mm:ss")));
        return orderSeq;
    }

    /**
     * 新增积分订单
     *
     * @param openId
     * @param scoreOrderRequest
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String addScoreOrder(String openId, ScoreOrderRequest scoreOrderRequest) {
        OrderBean dbOrderBean = new OrderBean();
        dbOrderBean.setCreateDate(new Date());
        dbOrderBean.setOpenId(openId);
        dbOrderBean.setStatus(1);
        dbOrderBean.setOrderType(4);
        String orderSeq = BusinessUtil.getOrderSeq(1);
        dbOrderBean.setOrderId(orderSeq);
        GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(scoreOrderRequest.getGoodsId());
        if (null != goodsBean) {
            dbOrderBean.setMerId(goodsBean.getMerId());
            dbOrderBean.setGoodsId(scoreOrderRequest.getGoodsId());
            dbOrderBean.setGoodsAttr(scoreOrderRequest.getGoodsAttr());
            dbOrderBean.setTotalNum(scoreOrderRequest.getTotalNum());
        } else {
            throw new BusinessException("当前商品已下架");
        }
        List<GoodsScoreBean> goodsScoreBeanList = goodsScoreBeanMapper.selectByGoodsId(scoreOrderRequest.getGoodsId());
        if (CollectionUtils.isEmpty(goodsScoreBeanList)) {
            throw new BusinessException("当前商品不是积分兑换商品");
        }
        GoodsScoreBean goodsScoreBean = goodsScoreBeanList.get(0);
        if (goodsScoreBean.getIsOpen() == 0) {
            throw new BusinessException("当前商品未开启积分兑换");
        }
        int needScore = goodsScoreBean.getScore();
        int needMoney = goodsScoreBean.getMoney();
        UserBean userBean = userBeanMapper.selectByOpenId(openId);
        if (userBean.getScore() < needScore * scoreOrderRequest.getTotalNum()) {
            throw new BusinessException("您的可用积分不足！");
        }
        List<GoodsAttrValueBean> goodsAttrValueBeanList = goodsAttrValueBeanMapper.selectByByGoodsIdAndSuk(scoreOrderRequest.getGoodsId(), scoreOrderRequest.getGoodsAttr(), 1);
        if (CollectionUtils.isEmpty(goodsAttrValueBeanList)) {
            log.error("【商品 goodsId = {} suk = {} 规格为空】", scoreOrderRequest.getGoodsId(), scoreOrderRequest.getGoodsAttr());
            if (goodsBean.getStock() <= 0) {
                throw new BusinessException("当前商品已售罄");
            }
            if (scoreOrderRequest.getTotalNum() > goodsBean.getStock()) {
                throw new BusinessException("当前商品库存不足，只剩下：" + goodsBean.getStock() + "个");
            }
        } else {
            if (goodsAttrValueBeanList.get(0).getStock() <= 0) {
                throw new BusinessException("当前商品已售罄");
            }
            if (scoreOrderRequest.getTotalNum() > goodsAttrValueBeanList.get(0).getStock()) {
                throw new BusinessException("当前商品库存不足，只剩下：" + goodsAttrValueBeanList.get(0).getStock() + "个");
            }
        }
        dbOrderBean.setTotalPrice(needMoney);
        orderBeanMapper.insert(dbOrderBean);
        taskService.saveTask(new TaskBean(1, orderSeq, DateFormatUtils.format(DateUtils.addDays(dbOrderBean.getCreateDate(), 1), "yyyy-MM-dd HH:mm:ss")));
        return orderSeq;
    }

    @Transactional(rollbackFor = Exception.class)
    public String addOrder(String openId, OrderBean orderBean) {
        orderBean.setCreateDate(new Date());
        orderBean.setOpenId(openId);
        orderBean.setStatus(1);
        orderBean.setOrderType(1);
        String orderSeq = BusinessUtil.getOrderSeq(1);
        orderBean.setOrderId(orderSeq);
        GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(orderBean.getGoodsId());
        if (null != goodsBean) {
            orderBean.setMerId(goodsBean.getMerId());
        } else {
            throw new BusinessException("当前商品已下架");
        }

        UserBean userBean = userBeanMapper.selectByOpenId(openId);
        List<GoodsAttrValueBean> goodsAttrValueBeanList = goodsAttrValueBeanMapper.selectByByGoodsIdAndSuk(orderBean.getGoodsId(), orderBean.getGoodsAttr(), 1);
        int totalPrice = 0;
        if (CollectionUtils.isEmpty(goodsAttrValueBeanList)) {
            log.error("【商品 goodsId = {} suk = {} 规格为空】", orderBean.getGoodsId(), orderBean.getGoodsAttr());
            if (goodsBean.getStock() <= 0) {
                throw new BusinessException("当前商品已售罄");
            }
            if (orderBean.getTotalNum() > goodsBean.getStock()) {
                throw new BusinessException("当前商品库存不足，只剩下：" + goodsBean.getStock() + "个");
            }
            if (null != userBean && userBean.getIsVip() == 1 && goodsBean.getVipPrice() != null) {
                totalPrice = goodsBean.getVipPrice() * orderBean.getTotalNum();
            } else {
                totalPrice = goodsBean.getPrice() * orderBean.getTotalNum();
            }
        } else {
            if (goodsAttrValueBeanList.get(0).getStock() <= 0) {
                throw new BusinessException("当前商品已售罄");
            }
            if (orderBean.getTotalNum() > goodsAttrValueBeanList.get(0).getStock()) {
                throw new BusinessException("当前商品库存不足，只剩下：" + goodsAttrValueBeanList.get(0).getStock() + "个");
            }
            if (null != userBean && userBean.getIsVip() == 1 && goodsBean.getVipPrice() != null) {
                totalPrice = Integer.parseInt(goodsAttrValueBeanList.get(0).getVipPrice()) * orderBean.getTotalNum();
            } else {
                totalPrice = Integer.parseInt(goodsAttrValueBeanList.get(0).getPrice()) * orderBean.getTotalNum();
            }
        }
        if (totalPrice <= 0) {
            throw new BusinessException("新增订单失败，商品价格不正确");
        }
        orderBean.setTotalPrice(totalPrice);
        orderBeanMapper.insert(orderBean);
        taskService.saveTask(new TaskBean(1, orderSeq, DateFormatUtils.format(DateUtils.addDays(orderBean.getCreateDate(), 1), "yyyy-MM-dd HH:mm:ss")));
        return orderSeq;
    }

    /**
     * 合并订单
     *
     * @param orderBeanList
     * @return
     */
    public List<OrderMergeBean> mergeOrders(List<OrderBean> orderBeanList, ModelMap modelMap) {
        List<OrderMergeBean> orderMergeBeanList = new ArrayList<>();
        int totalMoney = 0;
        if (CollectionUtils.isNotEmpty(orderBeanList)) {
            Map<String, List<OrderBean>> mergeMap = orderBeanList.stream().collect(Collectors.groupingBy(OrderBean::getOrderId));
            for (Map.Entry<String, List<OrderBean>> entry : mergeMap.entrySet()) {
                List<OrderBean> valueList = entry.getValue();
                for (OrderBean orderBean : valueList) {
                    GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(orderBean.getGoodsId());
                    if (null != goodsBean) {
                        orderBean.setImage(goodsBean.getImage());
                        orderBean.setGoodsName(goodsBean.getGoodsName());
                    }
                    orderBean.setWebSinglePrice(BusinessUtil.getWebAmount(orderBean.getTotalPrice() / orderBean.getTotalNum()));
                }
                OrderMergeBean orderMergeBean = new OrderMergeBean();
                orderMergeBean.setOrderSeq(entry.getKey());
                orderMergeBean.setOrderType(valueList.get(0).getOrderType());
                orderMergeBean.setStatus(valueList.get(0).getStatus());
                orderMergeBean.setStatusName(BusinessUtil.getOrderStatusName(valueList.get(0).getStatus()));
                orderMergeBean.setTotalNum(entry.getValue().size());
                int sumMoney = entry.getValue().stream().mapToInt(OrderBean::getTotalPrice).sum();
                orderMergeBean.setWebTotalPrice(BusinessUtil.getWebAmount(sumMoney));
                orderMergeBean.setChangeDate(valueList.get(0).getUpdateDate() == null ? valueList.get(0).getCreateDate() : valueList.get(0).getUpdateDate());
                orderMergeBean.setCartInfo(entry.getValue());
                if (valueList.get(0).getOrderType() == 3 && !StringUtils.isEmpty(valueList.get(0).getGroupNum())) {
                    //拼团订单
                    long groupNum = orderBeanMapper.countByGroupNum(valueList.get(0).getGroupNum());
                    orderMergeBean.setGroupNum((int) groupNum);
                }
                orderMergeBeanList.add(orderMergeBean);
                totalMoney += sumMoney;
            }
            Collections.sort(orderMergeBeanList, new Comparator<OrderMergeBean>() {
                @Override
                public int compare(OrderMergeBean o1, OrderMergeBean o2) {
                    return o2.getChangeDate().compareTo(o1.getChangeDate());
                }
            });
        }
        modelMap.put("totalOrder", orderMergeBeanList.size());
        modelMap.put("totalMoney", BusinessUtil.getWebAmount(totalMoney));
        return orderMergeBeanList;
    }

    public List<OrderMergeBean> selectByOpenId(String openId, String status, ModelMap modelMap) {
        List<OrderBean> orderBeanList = orderBeanMapper.selectByOpenId(openId, Integer.parseInt(status));
        List<OrderMergeBean> orderMergeBeanList = mergeOrders(orderBeanList, modelMap);//合并订单
        List<Map<Integer, Integer>> staticMap = orderBeanMapper.groupByStatus(openId);
        Map<String, Integer> dataMap = new HashMap<>();
        dataMap.put("status1", 0);
        dataMap.put("status2", 0);
        dataMap.put("status3", 0);
        dataMap.put("status4", 0);
        dataMap.put("status5", 0);
        dataMap.put("status6", 0);
        if (CollectionUtils.isNotEmpty(staticMap)) {
            staticMap.stream().forEach(c -> {
                dataMap.put("status" + c.get("STATUS"), c.get("num"));
            });
        }
        modelMap.put("groupOrder", dataMap);
        return orderMergeBeanList;
    }

    public List<Map<Integer, Integer>> groupByStatus(String openId) {
        return orderBeanMapper.groupByStatus(openId);
    }

    public OrderBean selectDetail(String id) {
        OrderBean orderBean = orderBeanMapper.selectByPrimaryKey(Integer.parseInt(id));
        if (null != orderBean) {
            orderBean.setStatusName(BusinessUtil.getOrderStatusName(orderBean.getStatus()));
            orderBean.setWebSinglePrice(BusinessUtil.getWebAmount(orderBean.getTotalPrice() / orderBean.getTotalNum()));
            orderBean.setWebTotalPrice(BusinessUtil.getWebAmount(orderBean.getTotalPrice()));
            orderBean.setWebPayPrice(BusinessUtil.getWebAmount(orderBean.getPayPrice()));
            orderBean.setShouldPayDate(DateUtils.addDays(orderBean.getCreateDate(), 1));
            UserBean userBean = userBeanMapper.selectByOpenId(orderBean.getOpenId());
            if (null != userBean) {
                orderBean.setNickName(userBean.getNickName());
            }
            GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(orderBean.getGoodsId());
            if (null != goodsBean) {
                orderBean.setGoodsName(goodsBean.getGoodsName());
                orderBean.setImage(goodsBean.getImage());
            }
        }
        return orderBean;
    }

    public OrderMergeBean selectMergeDetail(String orderSeq) {
        List<OrderBean> orderBeanList = orderBeanMapper.selectByOrderId(orderSeq);
        OrderMergeBean orderMergeBean = new OrderMergeBean();
        if (CollectionUtils.isNotEmpty(orderBeanList)) {
            orderBeanList.stream().forEach(c -> {
                if (c.getPayPrice() == null) {
                    c.setPayPrice(0);
                }
                if (c.getTotalPrice() == null) {
                    c.setTotalPrice(0);
                }
                c.setWebSinglePrice(BusinessUtil.getWebAmount(c.getTotalPrice() / c.getTotalNum()));
                GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(c.getGoodsId());
                if (null != goodsBean) {
                    c.setGoodsName(goodsBean.getGoodsName());
                    c.setImage(goodsBean.getImage());
                }
            });
            orderMergeBean.setOrderSeq(orderSeq);
            orderMergeBean.setOrderType(orderBeanList.get(0).getOrderType());
            orderMergeBean.setStatus(orderBeanList.get(0).getStatus());
            orderMergeBean.setStatusName(BusinessUtil.getOrderStatusName(orderBeanList.get(0).getStatus()));
            orderMergeBean.setTotalNum(orderBeanList.size());
            int sumMoney = orderBeanList.stream().mapToInt(OrderBean::getTotalPrice).sum();
            orderMergeBean.setWebTotalPrice(BusinessUtil.getWebAmount(sumMoney));
            orderMergeBean.setChangeDate(orderBeanList.get(0).getUpdateDate() == null ? orderBeanList.get(0).getCreateDate() : orderBeanList.get(0).getUpdateDate());
            orderMergeBean.setPayType(orderBeanList.get(0).getPayType());
            orderMergeBean.setUseScore(orderBeanList.get(0).getUserScore());
            orderMergeBean.setWebPayPrice(BusinessUtil.getWebAmount(orderBeanList.get(0).getPayPrice()));
            orderMergeBean.setShouldPayDate(DateUtils.addDays(orderBeanList.get(0).getCreateDate(), 1));
            orderMergeBean.setCreateDate(orderBeanList.get(0).getCreateDate());
            orderMergeBean.setUserName(orderBeanList.get(0).getUserName());
            orderMergeBean.setUserPhone(orderBeanList.get(0).getUserPhone());
            orderMergeBean.setUserAddress(orderBeanList.get(0).getUserAddress());
            orderMergeBean.setCartInfo(orderBeanList);
        }
        return orderMergeBean;
    }

    public List<GoodsBean> selectOrderGoodsByOrderId(String orderId, ModelMap modelMap) {
        List<OrderBean> orderBeanList = orderBeanMapper.selectByOrderId(orderId);
        List<GoodsBean> returnList = new ArrayList<>();
        final int[] totalPrice = {0};
        final int[] totalNum = {0};
        final int[] orderType = {0};
        final int[] totalScore = {0};
        final int[] totalMoney = {0};
        if (CollectionUtils.isNotEmpty(orderBeanList)) {
            for (OrderBean c : orderBeanList) {
                GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(c.getGoodsId());
                if (null != goodsBean.getIsScore() && goodsBean.getIsScore() == 1) {
                    //积分兑换商品
                    GoodsScoreBean goodsScoreBean = goodsScoreService.getGoodsScore(goodsBean.getId());
                    if (null != goodsScoreBean) {
                        totalScore[0] = goodsScoreBean.getScore() * c.getTotalNum();
                        totalMoney[0] = goodsScoreBean.getMoney() * c.getTotalNum();
                    }
                }
                goodsBean.setGoodsAttr(c.getGoodsAttr());
                goodsBean.setAddNum(c.getTotalNum());
                goodsBean.setWebTotalPrice(BusinessUtil.getWebAmount(c.getTotalPrice()));
                goodsBean.setWebPrice(BusinessUtil.getWebAmount(c.getTotalPrice() / c.getTotalNum()));
                totalPrice[0] += c.getTotalPrice();
                totalNum[0] += c.getTotalNum();
                orderType[0] = c.getOrderType();
                returnList.add(goodsBean);
            }
        }
        modelMap.put("totalPrice", BusinessUtil.getWebAmount(totalPrice[0]));
        modelMap.put("totalNum", totalNum[0]);
        modelMap.put("orderType", orderType[0]);
        modelMap.put("totalScore", totalScore[0]);
        modelMap.put("totalMoney", BusinessUtil.getWebAmount(totalMoney[0]));
        return returnList;
    }

    public void updateStatus(int status, String orderSeq) {
        orderBeanMapper.updateStatusByOrderId(status, orderSeq);
    }

    public void updatePayPrice(int status, int payPrice, int id) {
        orderBeanMapper.updatePayPrice(status, payPrice, id);
    }

    public void updateGroupPayPrice(String groupNum, int status, int payPrice, int id) {
        orderBeanMapper.updateGroupPayPrice(groupNum, status, payPrice, id);
    }

    public void updateStatusByGroupNum(int status, String groupNum) {
        orderBeanMapper.updateStautsByGroupNum(status, groupNum);
    }

    public void updatePayTypeByOrderSeq(String orderSeq, int payType) {
        orderBeanMapper.updatePayTypeByOrderSeq(payType, orderSeq);
    }

    /**
     * 取消订单
     *
     * @param orderSeq
     */
    public void deleteOrder(String orderSeq) {
        List<OrderBean> orderBeanList = orderBeanMapper.selectByOrderId(orderSeq);
        if (CollectionUtils.isEmpty(orderBeanList)) {
            throw new BusinessException("订单号不正确！");
        }
        OrderBean orderBean = orderBeanList.get(0);
        if (orderBean.getStatus() == 1) {
            //待付款
            orderBeanMapper.deleteByOrderId(orderSeq);
        } else {
            //申请退款
            orderRefundService.addOrderRefund(orderSeq);
        }
    }

    public void deleteOrders(String[] ids) {
        if (null != ids) {
            Arrays.stream(ids).forEach(c -> {
                OrderBean orderBean = orderBeanMapper.selectByPrimaryKey(Integer.parseInt(c));
                if (orderBean.getStatus() == 1) {
                    //待付款 已完成
                    orderBeanMapper.deleteByOrderId(orderBean.getOrderId());
                } else {
                    //申请退款
                    orderRefundService.addOrderRefund(orderBean.getOrderId());
                }
            });
        }
    }

    public List<OrderBean> selectByOrderId(String orderSeq) {
        return orderBeanMapper.selectByOrderId(orderSeq);
    }

    public JSONObject countByOpenId(String openId, String time, Date date) {
        List<OrderCount> countMap = orderBeanMapper.countByOpenId(openId, time, date);
        JSONObject jsonObject = new JSONObject();
        if (!CollectionUtils.isEmpty(countMap)) {
            for (OrderCount m : countMap) {
                String money = BusinessUtil.getWebAmount(m.getMoney());
                jsonObject.put("money", StringUtils.isEmpty(money) ? "0.0" : money);
                jsonObject.put("num", m.getNum());
                break;
            }
        }
        return jsonObject;
    }

    public Page listOrders(Page<OrderBean> pageInfo, OrderBean orderBean) {
        List<OrderBean> list = orderBeanMapper.listOrder(pageInfo, orderBean);
        if (CollectionUtils.isNotEmpty(list)) {
            list.stream().forEach(c -> {
                GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(c.getGoodsId());
                if (null != goodsBean) {
                    c.setGoodsName(goodsBean.getGoodsName());
                    c.setImage(goodsBean.getImage());
                    c.setWebSinglePrice(BusinessUtil.getWebAmount(c.getTotalPrice() / c.getTotalNum()));
                    c.setWebTotalPrice(BusinessUtil.getWebAmount(c.getTotalPrice()));
                    c.setWebPayPrice(BusinessUtil.getWebAmount(c.getPayPrice()));
                    c.setStatusName(BusinessUtil.getOrderStatusName(c.getStatus()));
                }
                UserBean userBean = userBeanMapper.selectByOpenId(c.getOpenId());
                if (null != userBean) {
                    c.setNickName(userBean.getNickName());
                }
            });
        }
        return pageInfo.setRecords(list);
    }

    public List<OrderBean> listOrdersAll(OrderBean orderBean) {
        List<OrderBean> list = orderBeanMapper.listOrderAll(orderBean);
        if (CollectionUtils.isNotEmpty(list)) {
            list.stream().forEach(c -> {
                GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(c.getGoodsId());
                if (null != goodsBean) {
                    c.setGoodsName(goodsBean.getGoodsName());
                    c.setImage(goodsBean.getImage());
                    c.setWebSinglePrice(BusinessUtil.getWebAmount(c.getTotalPrice() / c.getTotalNum()));
                    c.setWebTotalPrice(BusinessUtil.getWebAmount(c.getTotalPrice()));
                    c.setWebPayPrice(BusinessUtil.getWebAmount(c.getPayPrice()));
                    c.setStatusName(BusinessUtil.getOrderStatusName(c.getStatus()));
                }
                UserBean userBean = userBeanMapper.selectByOpenId(c.getOpenId());
                if (null != userBean) {
                    c.setNickName(userBean.getNickName());
                }
                if (c.getOrderType() == 1) {
                    c.setOrderTypeName("普通订单");
                } else if (c.getOrderType() == 2) {
                    c.setOrderTypeName("秒杀订单");
                } else if (c.getOrderType() == 3) {
                    c.setOrderTypeName("拼团订单");
                } else if (c.getOrderType() == 4) {
                    c.setOrderTypeName("积分订单");
                }
            });
        }
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateOrderInfo(OrderBean orderBean) {
        OrderBean returnBean = orderBeanMapper.selectByPrimaryKey(orderBean.getId());
        if (null != returnBean) {
            if (!StringUtils.isEmpty(orderBean.getCourierNo())) {
                if (StringUtils.isEmpty(orderBean.getUserPhone())) {
                    throw new BusinessException(500, "填了快递单号必须补充完收货人信息");
                }
                String courierNo = orderBean.getCourierNo();
                //快递号不为空
                if (orderBean.getCourierNo().startsWith("SF")) {
                    courierNo = courierNo + ":" + orderBean.getUserPhone().substring(orderBean.getUserPhone().length() - 4, orderBean.getUserPhone().length());
                }
                JSONObject jsonObject = KuaidiUtil.getKuaiDiDetail(courierNo);
                if (0 != jsonObject.getInteger("status")) {
                    throw new BusinessException(500, "快递号不正确，查询不到快递详情！");
                }
            }
            if (orderBean.getStatus() == 5 && returnBean.getStatus() != 5) {
                //购买完成 计算佣金和积分
                finishOrder(returnBean.getOrderId());
            }
            returnBean.setStatus(orderBean.getStatus());
            int totalPrice = BusinessUtil.getDbAmount(orderBean.getWebTotalPrice());
            int payPrice = BusinessUtil.getDbAmount(orderBean.getWebPayPrice());
            if (totalPrice < 0) {
                throw new BusinessException(500, "商品总价必须大于0！");
            }
            if (payPrice < 0) {
                throw new BusinessException(500, "实际支付金额必须大于0！");
            }
            returnBean.setTotalPrice(totalPrice);
            returnBean.setPayPrice(payPrice);
            returnBean.setUserName(orderBean.getUserName());
            returnBean.setUserPhone(orderBean.getUserPhone());
            returnBean.setUserAddress(orderBean.getUserAddress());
            returnBean.setCourierNo(orderBean.getCourierNo());
            orderBeanMapper.updateByPrimaryKey(returnBean);
            if (orderBean.getStatus() == 3 && returnBean.getStatus() != 3) {
                //已发货 发送一条提醒短信
                smsService.orderSendNotify(returnBean.getUserPhone(), returnBean);
                taskService.saveTask(new TaskBean(2, returnBean.getOrderId(), DateFormatUtils.format(DateUtils.addDays(new Date(), 10), "yyyy-MM-dd HH:mm:ss")));
            }
        }
    }

    public JSONObject statisOrder(int userId) {
        List<OrderBean> orderBeanList = orderBeanMapper.statisOrders();
        JSONObject jsonObject = new JSONObject();
        int yestoday = 0;
        int sendingNum = 0;
        int totalMoney = 0;
        if (CollectionUtils.isNotEmpty(orderBeanList)) {
            for (OrderBean orderBean : orderBeanList) {
                if (orderBean.getStatus() == 2) {
                    sendingNum++;
                }
                if (BusinessUtil.isYesterday(orderBean.getCreateDate())) {
                    sendingNum++;
                }
                if (userId == 0 && orderBean.getStatus() > 1) {
                    totalMoney += orderBean.getPayPrice();
                } else if (userId == orderBean.getMerId() && orderBean.getStatus() > 1) {
                    totalMoney += orderBean.getPayPrice();
                }
            }
        }
        jsonObject.put("yestoday", yestoday);
        jsonObject.put("sendingNum", sendingNum);
        jsonObject.put("totalMoney", BusinessUtil.getWebAmount(totalMoney));
        return jsonObject;
    }

    public String selectPhoneByCourierNo(String courierNo) {
        OrderBean orderBean = orderBeanMapper.selectPhoneByCourierNo(courierNo);
        if (null == orderBean) {
            return null;
        }
        return orderBean.getUserPhone();
    }

    public OrderBean selectUserInfo(String orderId) {
        return orderBeanMapper.selectUserInfo(orderId);
    }

    public int updateOrderId(String oldId, String newId) {
        return orderBeanMapper.updateOrderId(oldId, newId);
    }
}
